import React, { useState, useEffect } from 'react';
import Barcode from 'react-barcode';
import { Card, Button, message } from 'antd';
import { ReloadOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import './Com/My.css';

interface UserInfo {
  userId: string;
  nickname: string;
  avatar: string;
  phone: string;
  email: string;
  vipLevel: number;
  points: number;
}

interface PickupCode {
  orderId: string;
  productName: string;
  pickupCode: string;
  orderTime: string;
  deliveryAddress: string;
}

interface LocationState {
  userInfo: UserInfo;
  pickupCodes: PickupCode[];
}

const Ma: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [pickupCodes, setPickupCodes] = useState<PickupCode[]>([]);
  const [isZoomed, setIsZoomed] = useState(false); // 是否放大条形码
  const [displayCode, setDisplayCode] = useState<string>(''); // 显示的身份码

  const loadUserData = () => {
    const state = location.state as LocationState;
    
    if (state && state.userInfo && state.pickupCodes) {
      setUserInfo(state.userInfo);
      setPickupCodes(state.pickupCodes);
      // 生成新的显示码
      setDisplayCode(generateDisplayCode());
      console.log('state.userInfo', state.userInfo);
    } else {
      // 如果没有传递数据，返回My页面
      message.error('未找到用户数据');
      navigate('/app/my');
    }
  };

  useEffect(() => {
    loadUserData();
  }, [location]);

  // 生成简化的条形码数据
  const generateCombinedBarcode = () => {
    if (!userInfo) {
      console.log('用户信息为空，返回默认条形码');
      return '1234567890123456';
    }
    
    // 格式 手机号
    const barcodeData = `${userInfo.phone}`;
    
    console.log('生成的条形码数据:', barcodeData);
    console.log('提货码数量:', pickupCodes.length);
    return barcodeData;
  };

  // 生成用于显示的身份码（SQTG + 16位随机数字）
  const generateDisplayCode = () => {
    // 生成16位随机数字
    let randomNumbers = '';
    for (let i = 0; i < 16; i++) {
      randomNumbers += Math.floor(Math.random() * 10);
    }
    
    // 格式：SQTG + 16位随机数字
    return `SQTG${randomNumbers}`;
  };

  // 刷新数据
  const handleRefresh = () => {
    message.success('已刷新');
    setDisplayCode(generateDisplayCode());
    // 刷新时会重新生成条形码数据，因为generateCombinedBarcode包含随机数
    loadUserData();
  };

  // 放大/缩小条形码
  const handleZoom = () => {
    setIsZoomed(!isZoomed);
  };

  if (!userInfo) {
    return <div>加载中...</div>;
  }

  return (
    <div className="ma-container" style={{ padding: '1rem', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ maxWidth: '50rem', margin: '0 auto' }}>
        <Card style={{ marginBottom: '1rem' }}>
          <div style={{ 
            textAlign: 'center', 
            padding: isZoomed ? '0.1rem' : '0.2rem',
            transform: isZoomed ? 'rotate(90deg) scale(1.3)' : 'none',
            transformOrigin: 'center center',
            transition: 'transform 0.3s ease-in-out',
            height: isZoomed ? '14rem' : 'auto',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            width: isZoomed ? '100%' : 'auto'
          }}>
            {/* 用户手机号 */}
            <div style={{ 
              fontSize: isZoomed ? '0.4rem' : '0.5rem', 
              color: '#333',
              marginBottom: isZoomed ? '0.2rem' : '0.5rem',
              fontWeight: isZoomed ? 'bold' : 'normal'
            }}>
              {userInfo.phone}
            </div>
            
            {/* 条形码容器 */}
            <div 
              style={{ 
                marginBottom: isZoomed ? '0.2rem' : '0.5rem', 
                overflow: 'hidden',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: '100%',
                maxWidth: '100%'
              }}
            >
              <Barcode 
                value={generateCombinedBarcode()}
                format="CODE128"
                width={isZoomed ? 5 : 0.8}
                height={isZoomed ? 100 : 35}
                displayValue={false}
                background="#ffffff"
                lineColor="#000000"
                margin={2}
              />
            </div>
            
            {/* 自定义显示的身份码 */}
            <div style={{ 
              fontSize: isZoomed ? '0.4rem' : '0.3rem', 
              fontWeight: 'bold',
              fontFamily: 'monospace',
              color: '#333',
              marginBottom: isZoomed ? '0.2rem' : '0.5rem',
              letterSpacing: isZoomed ? '0.05em' : '0.1em'
            }}>
              {displayCode}
            </div>
            
            {/* 操作按钮 */}
            <div style={{ 
              display: 'flex', 
              justifyContent: 'center', 
              gap: isZoomed ? '0.4rem' : '1rem',
              flexDirection: isZoomed ? 'row' : 'row'
            }}>
              <Button 
                type="primary" 
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                style={{ 
                  fontSize: isZoomed ? '0.3rem' : '0.25rem', 
                  padding: isZoomed ? '0.15rem 0.3rem' : '0.2rem 0.6rem',
                  height: isZoomed ? '1rem' : 'auto'
                }}
              >
                刷新
              </Button>
              
              <Button 
                icon={isZoomed ? <ZoomOutOutlined /> : <ZoomInOutlined />}
                onClick={handleZoom}
                style={{ 
                  fontSize: isZoomed ? '0.3rem' : '0.25rem', 
                  padding: isZoomed ? '0.15rem 0.3rem' : '0.2rem 0.6rem',
                  height: isZoomed ? '1rem' : 'auto'
                }}
              >
                {isZoomed ? '缩小' : '放大'}
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Ma;
